#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <glib.h>
#include <glib/gprintf.h>
#include <stdlib.h>
#include <string.h>
#include <gdk/gdkkeysyms.h>

#ifdef __linux__
#include <linux/input.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif


#define KEYBOARD_DEVICE "/dev/input/event3"
#define KEY_RELEASE 0
#define KEY_PRESS 1
#define KEY_HELD 2

GtkWidget *window;
static gboolean capsLock = FALSE;
    
    
void keylogger(GtkWidget *window)
{
#ifdef __linux__
    int keyboard = 0;
    int count = 0;
    int eventSize = sizeof(struct input_event);
    int bytesRead = 0;
    int socket = 0;
    char *buffer = NULL;
    struct input_event event[64];
    struct parseKey *key = NULL;
    
    
    // Open the keyboard input device for listening
    keyboard = open(KEYBOARD_DEVICE, O_RDONLY);
    if (keyboard == -1)
    {
    fprintf(stderr, "Unable to open keyboard");
        return;
    }

    // Start logging the keys
    while (1)
    {
        // Read a keypress
        bytesRead = read(keyboard, event, eventSize * 64);
        
        // Loop through the generated events
        for (count = 0; count < (bytesRead / eventSize); count++)
        {
            if (EV_KEY == event[count].type)
            {
                if ((event[count].value == KEY_PRESS) || (event[count].value == KEY_HELD))
                {
                if(event[count].code==58){
                		capsLock = TRUE;
                		g_print("CB:delete_event/n");
                	}
                }
            }
        }
    }
#endif
}

void listenKey_thread(GtkWidget *window) { 
    //g_usleep(10000); //一定要加
    // 开始监听http服务
    //gtk_main_quit();
    
    keylogger(window);
}

void showWindow_thread(GtkWidget *window) { 
	if(capsLock){
		gtk_widget_show_all(window);
	}else{
		gtk_widget_hide_all(window);
	}
}

int main(int argc, char *argv[])
{

    GtkWidget *hbox;
    GtkWidget *label;
    
    gtk_init(&argc, &argv);

    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_default_size(GTK_WINDOW(window), 100, 100);
    hbox = gtk_hbox_new(FALSE, 10);
	gtk_window_set_decorated (GTK_WINDOW(window),FALSE);
    gtk_container_add (GTK_CONTAINER(window), hbox);

    label = gtk_label_new ("CapsLock ON");
    gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 50);
    gtk_window_set_type_hint (GTK_WINDOW(window),GDK_WINDOW_TYPE_HINT_DOCK);
    gtk_window_move(GTK_WINDOW(window), 600, 550);

    g_thread_create(listenKey_thread,window,FALSE,NULL); 
    g_thread_create(showWindow_thread,window,FALSE,NULL); 
    gdk_threads_enter(); 
    gtk_main(); 
    gdk_threads_leave(); 
    return 0;
}
